import {
	baseURL
} from '@/config/app.js'
import Request from 'luch-request'
import Base64 from 'base-64'
const request = new Request();

request.setConfig((config) => {

	/* config 为默认全局配置*/
	/* 根域名 */
	config.baseURL = baseURL,
		config.timeout = 20000,

		config.header = {

			'content-type': 'application/x-www-form-urlencoded'
			// 'content-type': 'application/json; charset=UTF-8',

		}

	return config
})


//请求前拦截
request.interceptors.request.use((config) => {
	
	const token = uni.getStorageSync('blade-auth');
	// console.log(config)
	//显示加裁框

	// 可使用async await 做异步操作
	config.headers = {
		...config.header,
	}
	config.header = {
		...config.header,
		'Captcha-Code': uni.getStorageSync('codes'),
		'blade-auth':'Bearer '+ token,
		
	};
	if(!config.data?.utf){
		console.log(config.data)
		config.header = {
			...config.header,
			'content-type': 'application/json; charset=UTF-8',
			}
		};
		
	//获取存储的token

	// console.log(token)

	config.header.Authorization = `Basic ${Base64.encode("mini_app:mini_secret")}`;
	// uni.showToast({
	// 	title: config.msg,
	// 	icon: 'none'
	// })
	const siteId = uni.getStorageSync('site_id') || "";
	config.header['site-id'] = siteId;
	return config
}, config => {
	// 可使用async await 做异步操作
	Promise.reject(config)
})


// 请求后拦截器
request.interceptors.response.use(response => {

	console.log(response)

	if (response.code == 401) {
		uni.hideLoading()
		uni.showToast({
			title: '登录过期请重新登录',
			icon: 'none'
		})
		setTimeout(() => {
			uni.reLaunch({
				url: '/pages/login/login'
			})

		}, 1000);

	} else {
		if (response.data.code == 400) {
			uni.hideLoading()
			uni.showToast({
				title: "参数错误",
				icon: "none"
			})
		}
	}



	return response.data
}, (response) => { // 请求错误做点什么。可以使用async await 做异步操作
	uni.hideLoading()
	if (response.data.code == 500) {
		
	uni.showToast({
		title: "系统错误，请稍候再试",
		icon: "none"
	})
	}

	return Promise.reject(response)
})

export default request